#!/usr/bin/env python
# coding: utf-8

from rediscluster import client
import demjson
import random
from datetime import datetime, timedelta
debug_mode = True

#python3,本地测试用

class RedisClusterClient(object):

    instance = None
    city_show_num_pool_index_prix = "copShowNumIndex:"
    city_show_num_pool_list_prix = "copShowNumList:"
    last_call_info_prix = "LastCallInfo:"

    def __init__(self, conn_list):
        self.conn_list = conn_list
        RedisClusterClient.instance = self.connect()

    def connect(self):
        """
        init connection
        :return: object
        """
        try:
            # 非密码连接redis集群
            # redisconn = StrictRedisCluster(startup_nodes=self.conn_list)
            # 使用密码连接redis集群
            redisconn = client.RedisCluster(startup_nodes=self.conn_list)
            return redisconn
        except Exception as e:
            print(e)
            return None

    def get_state(self):
        """
        :return:
        """
        res = RedisClusterClient(self.conn_list).connect()
        if not res:
            return False

        dic = res.cluster_info()

        for i in dic:
            ip = i.split(":")[0]
            if dic[i].get('cluster_state'):
                print("status, ip: ", ip, "value: ", dic[i].get('cluster_state'))

    def get_cop_show_num_dict(self, user_id):
        key = "copShowNumMap:%s" % user_id
        return RedisClusterClient.instance.hgetall(name=key)

    def get_cop_num(self, user_id, city=None):

        b_show_num_dict = self.get_cop_show_num_dict(user_id)
        if b_show_num_dict is None:
            return None
        if debug_mode:
            for k in b_show_num_dict.keys():
                print(k.decode('utf-8') + " : " + b_show_num_dict[k].decode('utf-8') + "\n")
        if city is None:
            """
            direct random one if without city param
            """
            if len(b_show_num_dict) > 0:
                rl = list(b_show_num_dict.keys())
                return random.choice(rl).decode('utf-8')
        else:
            """
            random one in a city showNum list
            """
            tmp = {x.decode('utf-8'): y.decode('utf-8') for x, y in b_show_num_dict.items()}
            print("tmp:")
            print(tmp)
            show_num_list = [x for x, y in tmp.items() if y is city]
            if len(show_num_list) > 0:
                return random.choice(show_num_list)

        return None

    def add_last_call_info(self, show_num, target_call_phone, call_info_dict):
        key = RedisClusterClient.last_call_info_prix + show_num + ":" + target_call_phone
        RedisClusterClient.instance.hmset(key, call_info_dict)
        RedisClusterClient.instance.expire(key, timedelta(days=30))
        # pipe = RedisClusterClient.instance.pipeline()
        # pipe.hmset(key, call_info_dict)
        # pipe.expire(key, timedelta(days=30))
        # pipe.execute()

    def get_last_call_info(self, key):
        b_last_call_info_dict = RedisClusterClient.instance.hgetall(key)
        if debug_mode:
            for k in b_last_call_info_dict.keys():
                print(k.decode('utf-8') + " : " + b_last_call_info_dict[k].decode('utf-8') + "\n")
                if b_last_call_info_dict[k] is dict:
                    for kk in b_last_call_info_dict[k].keys():
                        print(kk.decode('utf-8') + " : " + b_last_call_info_dict[k][kk].decode('utf-8') + "\n")
        return  b_last_call_info_dict


nodes = [
    {'host': '172.16.200.35', 'port': 6379},
    {'host': '172.16.200.36', 'port': 6379},
    {'host': '172.16.200.37', 'port': 6379},
    {'host': '172.16.200.38', 'port': 6379},
    {'host': '172.16.200.39', 'port': 6379},
    {'host': '172.16.200.40', 'port': 6379}
]
# init
rdc = RedisClusterClient(nodes)

if __name__ == '__main__':
    # rdc.get_cop_num('20358')
    # rdc.get_last_call_info('LastCallInfo:02023398853:13724059427')
    # print("none city:"+rdc.get_cop_num('20358'))
    print("with city:"+rdc.get_cop_num('20358','1'))

    #a = 20358
    #b = 1
    # rdc.get_cop_num('20358')
    # rdc.get_last_call_info('LastCallInfo:02023398853:13724059427')